package d08_接受和发送者;

import java.io.*;
import java.net.Socket;

public class  ServerReaderThread extends Thread{
    private Socket socket;
    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (true) {
                try {
                    String message = dis.readUTF();
                    sendMessage(message);
                    System.out.println(message);
                } catch (IOException e) {
                    System.out.println(socket.getRemoteSocketAddress()+"客户端已离线");
                    Server.list.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void sendMessage(String message) throws IOException {
        for (Socket soc : Server.list) {
            OutputStream os = soc.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(message);
            dos.flush();
        }
    }
}
